import React, {useEffect, useMemo, useState} from 'react'
import {Space, Button, Popconfirm, message} from 'antd'
import {history, connect} from 'umi'
import {
	PlusOutlined,
	ArrowDownOutlined,
	ArrowUpOutlined,
} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import {FleetColums, fleetFormItemType} from '../constant'
import {
	getFleetList,
	getFleetDriverStatistics,
	getImportData,
	getErrorListPage,
	deleteFleet,
} from '@/service/customer/fleet'
import SearchForm from '@/components/SearchForm'
import {numberStrFormat} from '@/utils/common'
import styles from './index.less'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import Permissions from '@/components/Permissions'
import {downloadDocumentUrl} from '@/service/common/download'
import CustomTable from '@/components/Table'

interface DataType {
	fleetName: string
	captainName: string
	affiliatedCompanyName: string
	reason: string
}

const list = ({user}: any) => {
	const orgId = useMemo(() => user.orgId, [user])
	const [dataList, setDataList] = useState<any[]>([])

	const [statistics, setStatistics] = useState({
		ontheJob: 0,
		Separation: 0,
		fleetCount: 0,
		driverCount: 0,
	})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [searchData, setSearchData] = useState<any>({})
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const FormItems: any[] = useMemo(
		() => [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'fleetName',
						name: 'fleetName',
						label: '车队名称',
					},
					{
						type: 'input',
						key: 'captainName',
						name: 'captainName',
						label: '车队长名称',
					},
					{
						type: 'input',
						key: 'captainPhone',
						name: 'captainPhone',
						label: '车队长电话',
					},
				],
			},
		],
		[],
	)

	const openReviewPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/fleet/detail',
			query: {
				type: 'detail',
				id: record.id,
				orgId,
			},
		})
	}

	const openEditPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/fleet/edit',
			query: {
				type: 'edit',
				id: record.id,
				orgId,
			},
		})
	}

	const getData = () => {
		setLoading(true)
		getFleetList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataList(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataList([])
				message.error(err)
				setLoading(false)
			})
	}

	// 获取统计数据
	const getStatistics = async () => {
		const data = await getFleetDriverStatistics()
		if (data.code === 0) {
			setStatistics(data.data)
		}
	}

	useEffect(() => {
		if (!user.orgId) return
		getStatistics()
	}, [user])

	useEffect(() => {
		getData()
	}, [params])

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '车队长名称',
			dataIndex: 'captainName',
			align: 'center',
		},
		{
			title: '车队长手机号',
			dataIndex: 'captainPhone',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
		},
	]

	const onDelete = async (id: string) => {
		const data = await deleteFleet({
			ids: id,
		})
		if (data.code === 0) {
			message.success('删除成功')
			getData()
			getStatistics()
		}
	}

	const getColnums: any[] = useMemo(
		() => [
			...FleetColums,
			{
				title: '操作',
				dataIndex: 'operation',
				align: 'center',
				fixed: 'right',
				width: 200,
				render: (field: 'string', record: Record<string, string>) => (
					<Space size={12}>
						<Permissions permissionID="amc_customer_fleet_list_review">
							<Button
								type="link"
								onClick={() => openReviewPage(record)}>
								查看
							</Button>
						</Permissions>

						<Permissions permissionID="amc_customer_fleet_list_edit">
							<Button
								type="link"
								onClick={() => openEditPage(record)}>
								编辑
							</Button>
						</Permissions>

						<Permissions permissionID="amc_customer_fleet_list_delete">
							<Popconfirm
								placement="topLeft"
								title={`确定删除 ${record?.fleetName} 车队吗？删除后，该车队下的车辆或司管员将不属于该车队。`}
								onConfirm={() => onDelete(record.id)}
								okText="确定"
								cancelText="取消">
								<Button type="link">删除</Button>
							</Popconfirm>
						</Permissions>
					</Space>
				),
			},
		],
		[dataList],
	)

	const onExportClick = () => {
		let queryDesc = ''
		Object.keys(searchData).forEach((item) => {
			queryDesc += `${fleetFormItemType[item]}：${searchData[item]};`
		})
		downloadDocumentUrl({
			resourceId: '102',
			queryDesc,
			queryParam: searchData,
		})
	}

	return (
		<div className={styles.fleet}>
			<div className={styles.statistics}>
				<div className={styles.item}>
					<div className={styles.count}>
						{numberStrFormat(statistics.fleetCount || 0)}个
					</div>
					<div className={styles.text}>
						<span className={styles.icon} />
						车队总数
					</div>
				</div>
				<div className={styles.item}>
					<div className={styles.count}>
						{numberStrFormat(statistics.driverCount || 0)}人
					</div>
					<div className={styles.text}>
						<span className={styles.icon} /> 司机总数
					</div>
				</div>
				<div className={styles.item}>
					<div className={styles.count}>
						{numberStrFormat(statistics.ontheJob || 0)}人
					</div>
					<div className={styles.text}>
						<span className={styles.icon} /> 在职司机数
					</div>
				</div>
				<div className={styles.item}>
					<div className={styles.count}>
						{numberStrFormat(statistics.Separation || 0)}人
					</div>
					<div className={styles.text}>
						<span className={styles.icon} /> 离职司机数
					</div>
				</div>
			</div>
			<div className={styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '90px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={FormItems}
					onReset={() => {
						setSearchData({})
						setParams({
							current: 1,
							size: 10,
						})
					}}
					onFinish={(value) => {
						setSearchData(value)
						setParams({
							current: 1,
							size: 10,
						})
					}}
				/>
			</div>
			<div className={styles.content}>
				<div className={styles.btnList}>
					<Permissions permissionID="amc_customer_fleet_list_add">
						<Button
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push({
									pathname: '/fleet/add',
									query: {
										type: 'add',
									},
								})
							}}>
							新增
						</Button>
					</Permissions>
					<Permissions permissionID="amc_customer_fleet_list_import">
						<Button
							icon={<ArrowUpOutlined />}
							className={styles.warning}
							ghost
							size="small"
							onClick={() => setIsUploadModalOpen(true)}>
							导入
						</Button>
					</Permissions>

					<Permissions permissionID="amc_customer_fleet_list_export">
						<Button
							icon={<ArrowDownOutlined />}
							className={styles.import}
							ghost
							size="small"
							onClick={onExportClick}>
							导出
						</Button>
					</Permissions>
				</div>
				<CustomTable
					params={params}
					columns={getColnums}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataList}
				/>
			</div>

			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportData}
				onTableList={getErrorListPage}
				getListData={getData}
				uploadFileUrl={`${modalApi.customer}/fleet/import/check`}
				columns={errorColumns}
				sourceId={13}
				templateType="车队导入"
			/>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(list)
